package 顺序表;

import java.util.Arrays;

public class ArrayList implements Operation{
    public int[] elem;
    public int usedsize;
    public static final int DEFAULT_CAPACITY =5;

    public ArrayList(){
        elem =new int[DEFAULT_CAPACITY];
    }
    @Override
    public void add(int data){
        //添加数据,默认添加到最后位置
        if(isFull()){
            Arrays.copyOf(elem,2*elem.length);//扩容
        }
        elem[usedsize] = data;
        usedsize++;

    }

    @Override
    public boolean isFull() {
        return usedsize==elem.length;
    }

    @Override
    public void add(int pos,int data){
        //在某位置添加元素
        chackPosOfAdd(pos);
        if (isFull()){
            Arrays.copyOf(elem,2*elem.length);
        }
        for (int i = usedsize-1; i >=pos ; i--) {
            elem[i+1] = elem[i];
        }
        elem[pos] = data;
        usedsize++;
    }
    public void chackPosOfAdd(int pos){
        //判断pos位置
        if(pos<0||pos>usedsize){
            throw new PosException("插入位置错误");
        }
    }
    @Override
    public boolean contains(int toFound){
        for (int i = 0; i < usedsize; i++) {
            if(toFound==elem[i]){
                return true;
            }
        }
        return false;
    }
    @Override
    public int indexOf(int toFound){
        for (int i = 0; i < usedsize; i++) {
            if(toFound==elem[i]){
                return i;
            }
        }
        return -1;
    }
    @Override
    public int get(int pos){
        chackPosOfAdd(pos);
        if(isEmpty()){
            throw new EmptyException("顺序表为空!");
        }
        return elem[pos];
    }
    @Override
    public void set(int pos,int value){
        //更新pos位置的值
        chackPosOfAdd(pos);
        if(isEmpty()){
            throw new EmptyException("顺序表为空!");
        }
        this.elem[pos] =value;
    }
    @Override
    public void remove(int toRemove){
        if(isEmpty())
        {
            throw new EmptyException("顺序表为空!");
        }
        int index = indexOf(toRemove);
        for (int i = index; i <usedsize-1 ; i++) {
            elem[i] = elem[i+1];
        }
        usedsize--;
    }
    @Override
    public int size(){
        return usedsize;
    }
    @Override
    public void clean(){
        usedsize=0;
    }
    @Override
    public void display(){
        //输出所有元素
        for (int i = 0; i <usedsize ; i++) {
            System.out.print(elem[i]+" ");
        }
        System.out.println();
    }

    public boolean isEmpty(){
        return usedsize==0;
    }
}
